<script setup>
import {
    ref,
    reactive,
    onBeforeMount,
    onMounted,
    onBeforeUpdate,
    onUpdated,
    onBeforeUnmount,
    onUnmounted,
    computed,
    toRefs
} from "vue";

let props = defineProps({
    data_list: {
        type: Array,
        default: () => {
            return [
                { text: '元素 1--sort2', color: '#1677ff', sort: 2 },
                { text: '元素 2--sort3', color: '#52c41a', sort: 3 },
                { text: '元素 3--sort1', color: '#faad14', sort: 1 },
                { text: '元素 4--sort4', color: 'red', sort: 4 },
            ]
        }
    },
    class_name:{
        type: String,
        default:()=>{
            return 'drag_ele'
        }
    },
    class_name_wrap:{
        type: String,
        default:()=>{
            return 'drag_ele_wrap'
        }
    }
});


let props_data_list=ref(props.data_list);


const draggingIndex = ref(-1);
const offset = reactive({ x: 0, y: 0 });
const startPos = reactive({ x: 0, y: 0 });
const wrapRects = ref([]);
const target_index = ref(-1);


// 按sort排序后的元素
const props_data_list_sort = computed(() => {
    return [...props_data_list.value].sort((a, b) => {
        console.log("a",a)
        return a.sort - b.sort
    })
});


function startDrag(index, e, dragger_ele, dragger_ele_wrap) {

    console.log(index, e, dragger_ele, dragger_ele_wrap)
    // 确保点击的是动态元素


    draggingIndex.value = index;
    const dragElement = e.target;

    // 记录所有包裹层的位置
    wrapRects.value = Array.from(document.querySelectorAll(`.${dragger_ele_wrap}`))
        .map(el => el.getBoundingClientRect());

    // 记录初始位置
    const rect = dragElement.getBoundingClientRect();
    console.log("drag_ele", dragger_ele)
    if (!e.target.classList.contains(dragger_ele)) return;



    startPos.x = e.clientX - rect.left;
    startPos.y = e.clientY - rect.top;

    // 设置拖拽元素定位
    dragElement.style.position = 'absolute';
    dragElement.style.width = `${rect.width}px`;



    window.addEventListener('mousemove', handleDrag);
    window.addEventListener('mouseup', stopDrag);
};

function handleDrag(e) {
    if (draggingIndex.value === -1) return;

    // 计算偏移
    const wrapperRect = wrapRects.value[draggingIndex.value];
    offset.x = e.clientX - wrapperRect.left - startPos.x;
    offset.y = e.clientY - wrapperRect.top - startPos.y;

    // 碰撞检测
    target_index.value = -1;
    wrapRects.value.forEach((rect, index) => {
        if (index === draggingIndex.value || index >= props_data_list_sort.value.length) return;

        if (e.clientX > rect.left && e.clientX < rect.right &&
            e.clientY > rect.top && e.clientY < rect.bottom) {
            target_index.value = index;
        }
    });
};

function stopDrag() {
    // 交换sort属性
    if (target_index.value !== -1) {
        const currentElements = props_data_list_sort.value;
        const tempSort = currentElements[draggingIndex.value].sort;
        currentElements[draggingIndex.value].sort = currentElements[target_index.value].sort;
        currentElements[target_index.value].sort = tempSort;
    }

    // 重置状态
    setTimeout(() => {
        draggingIndex.value = -1;
        target_index.value = -1;
        offset.x = 0;
        offset.y = 0;

        document.querySelectorAll(`.${props.class_name}`).forEach(el => {
            el.style.position = '';
            el.style.width = '';
            el.style.height = '';
            el.style.transform = '';
        });

        window.removeEventListener('mousemove', handleDrag);
        window.removeEventListener('mouseup', stopDrag);
    }, 50);
};


onMounted(() => { })

onBeforeUnmount(() => { })

</script>

<template>
    <div class="dragger_wrap">
        <!-- 动态元素，按sort排序 -->
        <div v-for="(element, index) in props_data_list_sort" :key="index" :class="class_name_wrap">
            <div :class="class_name" :style="{
                backgroundColor: element.color,
                transform: draggingIndex === index ? `translate(${offset.x}px, ${offset.y}px)` : ''
            }" @mousedown="startDrag(index, $event, class_name, class_name)">
                <div>123456</div>
                {{ element.text }} (sort: {{ element.sort }})
            </div>
        </div>

    </div>
</template>

<style scoped>
.dragger_wrap {
    padding: 10px;
    padding-right: 0px;
    border-radius: 10px;
    padding-top: 20px;
    box-sizing: border-box;

    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    padding-right: 10px;

    min-height: 100px;

}

/* 保持原有样式不变 */
.drag_ele_wrap {
    display: inline-block;
    width: 30%;
    min-height: 60px;
    margin: 10px;
    position: relative;
}


.dragger_wrap {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.drag_ele {
    cursor: move;
    user-select: none;
    padding: 1rem;
    border-radius: 0.375rem;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease;
}

.drag_ele>*{
    cursor: default;
}

.drag_ele:active {
    box-shadow: 0 8px 12px -2px rgba(0, 0, 0, 0.15);
    z-index: 1000;
    transition: none;
}

.drag_ele_wrap {
    transition: transform 0.3s ease;
}
</style>
